package com.yd.mvc.pc.MessageController;

import com.yd.app.service.common.LoggerService;
import com.yd.app.service.pc.messageService.MessageService;
import com.yd.app.util.BusinessException;
import com.yd.domain.business.Message;
import com.yd.domain.commom.PageModel;
import com.yd.domain.searchParam.MessageParam;
import com.yd.domain.sys.DicEnum;
import com.yd.domain.sys.Logger;
import com.yd.mvc.baseController.BaseController;
import com.yd.mvc.baseController.util.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author zy
 * @create 2018-03-13 10:09
 * @desc
 **/
@RestController
@RequestMapping(value = "/api/message")
public class MessageController extends BaseController{
    @Autowired
    private MessageService messageService;
    @Autowired
    private LoggerService loggerService;
    /**
     * @Author: zy
     * @Desc: 录入信息
     * @Date:  2018/3/13
     * @Param
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void addMessage(@RequestBody Message message,HttpServletRequest request) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.MESSAGE_MANAGER);//验证权限
        }
        String addUser="admin";
        String suff="发起人:"+addUser+";接收人:"+message.getReceiveUser()+";内容:"+message.getContent();
        try {
            message.setPublishUser(addUser);//
            String str=message.getPublishUser()+message.getReceiveUser();
            message.setToken(str);
            messageService.addMessage(message);
            loggerService.addLogger(new Logger("新增信息记录",addUser,Logger.LOG_TYPE.ADD,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        } catch (Exception e) {
            loggerService.addLogger(new Logger("新增信息记录",addUser,Logger.LOG_TYPE.ADD,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
            e.printStackTrace();
        }
    }
    /**
     * @Author: zy
     * @Desc: 修改信息
     * @Date:  2018/3/13
     * @Param
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public void updateMessage(@RequestBody Message message,HttpServletRequest request) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.MESSAGE_MANAGER);//验证权限
        }
        String suff="发起人:"+user.getUserId()+";接收人:"+message.getReceiveUser()+";内容:"+message.getContent();
        try {
            messageService.updateMessage(message);
            loggerService.addLogger(new Logger("修改信息记录",user.getUserId(),Logger.LOG_TYPE.UPDATE,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        } catch (Exception e) {
            e.printStackTrace();
            loggerService.addLogger(new Logger("修改信息记录",user.getUserId(),Logger.LOG_TYPE.UPDATE,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        }
    }
    /**
     * @Author: zy
     * @Desc: 删除消息
     * @Date: 2018/3/13
     * @Param
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public void deleteMessage(@PathVariable("id") String id,HttpServletRequest request) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.MESSAGE_MANAGER);//验证权限
        }
        String suff="删除人："+user.getUserId()+",删除的id:"+id+",删除时间："+new Date();
        try {
            messageService.deleteMessage(id);
            loggerService.addLogger(new Logger("删除信息记录",user.getUserName(),Logger.LOG_TYPE.DELETE,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        } catch (Exception e) {
            e.printStackTrace();
            loggerService.addLogger(new Logger("删除信息记录",user.getUserName(),Logger.LOG_TYPE.DELETE,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        }
    }
    /**
     * @Author:
     * @Desc: 根据token清空 与某人的聊天记录
     * @Date: 2018/3/13
     * @Param
     */
    @RequestMapping(value = "/clean/{userId}", method = RequestMethod.DELETE)
    public void clearTalkMsg(@PathVariable("userId") String userId,HttpServletRequest request) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.MESSAGE_MANAGER);//验证权限
        }
        String suff="删除人："+user.getUserId()+",删除时间："+new Date();
        try {
            if(user!=null){
                messageService.cleanMessage(userId,user.getUserId());
                loggerService.addLogger(new Logger("删除信息记录",user.getUserName(),Logger.LOG_TYPE.DELETE,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            loggerService.addLogger(new Logger("删除信息记录",user.getUserName(),Logger.LOG_TYPE.DELETE,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        }
    }
    /**
     * @Author:
     * @Desc: 根据token清空 与某人的聊天记录
     * @Date: 2018/3/13
     * @Param
     */
    @RequestMapping(value = "/clean", method = RequestMethod.POST)
    public void mutClearTalkMsg(@RequestBody String[] userIds,HttpServletRequest request) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.MESSAGE_MANAGER);//验证权限
        }
        String suff="删除人："+user.getUserId()+",删除时间："+new Date();
        try {
            if(user!=null){
                for(String userId:userIds){
                    messageService.cleanMessage(userId,user.getUserId());
                }
                loggerService.addLogger(new Logger("删除信息记录",user.getUserName(),Logger.LOG_TYPE.DELETE,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            loggerService.addLogger(new Logger("删除信息记录",user.getUserName(),Logger.LOG_TYPE.DELETE,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        }
    }
    /**
     * @Author: zy
     * @Desc: 分页查询数据列表
     * @Date:  2018/3/9
     * @Param
     */
    @RequestMapping(value = "/list/{pageIndex}/{pageSize}", method = RequestMethod.POST)
    public PageModel getMessageList(@RequestBody MessageParam messageParam, @PathVariable("pageIndex")int pageIndex, @PathVariable("pageSize")int pageSize){
        //前台处理token的拼接，两个ID
        PageModel pm=messageService.getMessageList(messageParam,pageIndex,pageSize);
        return pm;
    }
    /**
     * 获取谈话记录
     * @return
     */
    @RequestMapping(value = "/talk/list/{userId}/{pageIndex}/{pageSize}", method = RequestMethod.GET)
    public PageModel getMessageTalkList(HttpSession session, @PathVariable("userId")String userId, @PathVariable("pageIndex")int pageIndex, @PathVariable("pageSize")int pageSize) throws BusinessException {
        //前台处理token的拼接，两个ID
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        PageModel pm=null;
        if(user!=null){
            pm=messageService.getMessageTalkForList(userId,user.getUserId(),pageIndex,pageSize);
            //数据获取成功---更新已读状态
            messageService.updateMessageIfRead(userId,user.getUserId(),true);
        }else{
            throw new BusinessException(401,"尚未登录","no-login");
        }
        return pm;
    }
    /**
     * @Author: zy
     * @Desc: 批量删除
     * @Date:  2018/3/13
     * @Param
     */
    @RequestMapping(value = "/deleteAll",method = RequestMethod.POST)
    public void deleteAll(@RequestBody Message message,HttpServletRequest request) throws BusinessException {
        AuthUtil.AuthedUser user = AuthUtil.getCurrentUser();
        String delUser="";
        if(user!=null){
            getIfHasPerm(AuthUtil.getCurrentUser(), DicEnum.PERM_CODE.MESSAGE_MANAGER);//验证权限
            delUser=user.getUserName();//后台自动获取，currentUser中；
        }
        String suff="删除人："+delUser+",批量删除的id:"+message.getStrMsg()+"删除时间："+new Date();
        try {
            String str=message.getStrMsg();
            String strN= str.substring(0,str.length()-1);//上面这两行代码是为了去除前台传过来的id字符串中最后一个多余的 "，"
            message.setStrMsg(strN);
            messageService.deleteAll(message);
            loggerService.addLogger(new Logger("批量删除信息记录",delUser,Logger.LOG_TYPE.DELETE,Logger.STATUS.SUCCESS,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
        }catch (Exception e){
            loggerService.addLogger(new Logger("批量删除信息记录",delUser,Logger.LOG_TYPE.DELETE,Logger.STATUS.FAIL,Logger.MODEL_TYPE.MSGINFO,"",suff),request);
            e.printStackTrace();
        }
    }
}
